<script lang="ts">
  let сurrency = { rates: { USD: 1} };
  let selected1 = 'USD'
  let selected2 = 'USD'
  $: first = 0
  $: second = 0
     const getCurrency = async () => {
        var response = await fetch('https://open.er-api.com/v6/latest/USD');
        var result = await response.json();
        return result;
    }
    сurrency = getCurrency();
</script>

<main>
  {#await сurrency}
    <h2>Loading....</h2>
{:then сurrency}
  <h1>Конвертер валют</h1>
     <form action="/" method="post">
       <label for="from">Выберите валюту:</label>
       <select name="from" id="from" bind:value={selected1} on:change={()=> (first = second/сurrency.rates[selected2]*сurrency.rates[selected1])}>
        {#each Object.keys(сurrency.rates) as item}
          <option  mValue = '{сurrency.rates[item]}' value="{item}">{item}</option>
        {/each}  
       </select>
       <select name="to" id="to" bind:value={selected2} on:change={() => (second = first/сurrency.rates[selected1]*сurrency.rates[selected2])}>
        {#each Object.keys(сurrency.rates) as item}
          <option  mValue = '{сurrency.rates[item]}' value="{item}">{item}</option>
        {/each}  
       </select>
       <p>
         <label for="amount">Введите сумму:</label>
         <input type="number" name="amount" id="amount" bind:value = {first} on:input={() => (second = first/сurrency.rates[selected1]*сurrency.rates[selected2])} fstep="0.01">
         <input type="number" name="amount" id="amount" bind:value={second} on:input={() => (first = second/сurrency.rates[selected2]*сurrency.rates[selected1])} inId = 'to' step="0.01">
       </p>
     </form>
     <a href="https://www.exchangerate-api.com">Курсы по API обменного курса</a>
{:catch err}
    <h2>Error while loading the data</h2>
{/await}
</main>